package net.zjitc.controller;


import net.zjitc.domain.MessageConstant;
import net.zjitc.domain.Result;
import net.zjitc.domain.ResultPage;
import net.zjitc.domain.User;
import net.zjitc.service.UserService;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public Result add(@RequestBody User user) {
        try{
            userService.addUser(user);
        }catch (Exception e){
            return new Result(false,MessageConstant.ADD_USER_FAIL,null);
        }
        return new Result(true,MessageConstant.ADD_USER_SUCCESS,null);
//        return userService.addUser(user);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        try{
            userService.deleteUser(id);
        }catch (Exception e){
            return new Result(false,MessageConstant.DELETE_USER_FAIL,null);
        }
        return new Result(true,MessageConstant.DELETE_USER_SUCCESS,null);
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        User user = null;
        try{
            user = userService.findById(id);
        }catch (Exception e){
            return new Result(false,MessageConstant.QUERY_USER_FAIL,null);
        }
        return new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
    }

    @PutMapping
    public Result update(@RequestBody User user) {
        try{
            userService.UpdateUser(user);
        }catch (Exception e){
            return new Result(false,MessageConstant.EDIT_USER_FAIL,null);
        }
        return new Result(true,MessageConstant.EDIT_USER_SUCCESS,null);
    }

    @PostMapping("/{currentPage}/{pageSize}")
    public Result findPage(@PathVariable("currentPage") int currentPage,
                           @PathVariable("pageSize") int pageSize,
                           @RequestBody User user) {
//        return userService.findPage(currentPage,pageSize,user);
        ResultPage<User> page = null;
        try {
            page = userService.findPage(currentPage, pageSize, user);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_USER_FAIL, null);
        }
        return new Result(true, MessageConstant.QUERY_USER_SUCCESS, page);
    }
}
